/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse;

import java.util.*;
import java.io.File;
import java.sql.*;

/**************
 * This class monitors files based on a typeID/appID pair from the metadata. It
 * tracks how much of a file has been processed.
 * 
 * @author bduphoff
 * 
 */

public class DataFileMonitor extends Thread {

    /********************
     * A collection of DataFileProcessor objects that tracks files being
     * processed by the system for this sensor/app pair.
     */
    private Vector<DataFileProcessor> fileProcessors = new Vector<DataFileProcessor>();

    /******************
     * The maximum number of file processors that can be active at any given
     * time. At this time only a value of 1 is thread safe. Need to add some
     * more code to have multiple files processed at once per type.
     */
    private int maxFileProcessors = 1;

    /****************
     * The type ID part of the sensor/app identifier for this instance.
     */
    private int typeID = -1;

    /****************
     * The application ID part of the sensor/app identifier for this instance.
     */
    private int appID = -1;

    /********************
     * A database connection used by this instance to access the system
     * metadata.
     */
    private MetaDatabase mdb = null;

    /***************
     * The number of milliseconds to wait if maxFileProcessors has been reached.
     */
    private int waitInterval = 10000;

    public int getWaitInterval() {
        return waitInterval;
    }

    public void setWaitInterval(int waitInterval) {
        this.waitInterval = waitInterval;
    }

    /***************
     * Constructor that allows the number of file processors to be set along
     * with the required sensor/app pair.
     * 
     * @param sensorID
     * @param appID
     * @param maxFileProcessors
     */
    public DataFileMonitor(int typeID, int appID, int maxFileProcessors) {
        this.typeID = typeID;
        this.appID = appID;
        this.maxFileProcessors = maxFileProcessors;
    }

    /***************
     * Creates a DataFileMonitor instance to process files for a given
     * sensor/app pair.
     * 
     * @param sensorID
     * @param appID
     */
    public DataFileMonitor(int typeID, int appID) {
        this.typeID = typeID;
        this.appID = appID;
    }

    /**********
     * Allows supporting classes to access the appID attribute.
     * 
     * @return The app ID attribute
     */
    public int getAppID() {
        return appID;
    }

    /*******
     * Updates the system metadata to indicate that a file has been processed.
     * Called by DataFileProcessor instance spawned by this instance of
     * DataFileMonitor.
     * 
     * @param fileID
     *            The file identifier to set as processed
     * @throws Exception
     */
    public void setFileProcessed(int fileID) throws Exception {
        Statement s = mdb.createStatement();
        String sql = "update data_files_by_app set Status=1 where App_ID=" + appID + " and File_ID=" + fileID;
        s.execute(sql);
        s.close();
    }

    public void setFileOffset(int fileID, int offset) throws Exception {
        Statement s = mdb.createStatement();
        String sql = "update data_files_by_app set Record_Offset=" + offset + " where App_ID=" + appID
                + " and File_ID=" + fileID;
        s.execute(sql);
        s.close();
    }

    /**********
     * Allows supporting classes to access the sensor ID attribute.
     * 
     * @return The sensor ID attribute
     */
    public int getTypeID() {
        return typeID;
    }

    public void run() {
        try {
            if (typeID == -1 || appID == -1) {
                throw (new Exception(
                        "Type/app ID pair was invalid. Must be non-negative and consistent with values in the system metadata."));
            }
            if (maxFileProcessors == -1) {
                throw (new Exception("Value for maxFileProcessors must be non-negative."));
            }

            // Create a connection to the system metadata
            mdb = MetaDatabase.create();

            // Loop forever until an Exception is thrown or the system exits.
            // Does not handle failure of the loop as well as it could.
            while (true) {

                // Check to see if any threads are done
                int idx = 0;
                while (idx < fileProcessors.size()) {
                    DataFileProcessor fileProcessor = (DataFileProcessor) fileProcessors.elementAt(idx);
                    if (!fileProcessor.isAlive()) {
                        fileProcessors.remove(idx);
                    } else {
                        idx++;
                    }
                }

                // If there are less than maxFileProcessors threads, start a
                // news one, otherwise wait
                if (fileProcessors.size() < maxFileProcessors) {

                    // Create the SQL clause to select a fileID not being
                    // processed already
                    String fileIdSQL = " and ";
                    for (int i = 0; i < fileProcessors.size(); i++) {
                        DataFileProcessor fileProcessor = (DataFileProcessor) fileProcessors.elementAt(i);
                        fileIdSQL += " a.File_ID != " + fileProcessor.getFileID() + " and ";
                    }

                    // Broken. need to a way to see if the file is already being
                    // processed by a thread

                    String sql = "select c.App_Class as App_Class, a.Path as Path, c.Name as Name, b.Record_Offset as Record_Offset, c.App_ID as App_ID, a.File_ID as File_ID, b.Status as Status, a.Sensor_ID as Sensor_ID from data_files a, data_files_by_app b, app_list c where a.Node_ID="
                            + NetFSE.NODE_ID
                            + " and a.Node_ID=c.Node_ID and a.File_ID=b.File_ID and b.App_ID=c.App_ID "
                            + fileIdSQL
                            + " a.Status=1 and b.Status=0 and a.Type_ID="
                            + typeID
                            + " and b.App_ID="
                            + appID
                            + " limit " + (maxFileProcessors - fileProcessors.size());

                    // System.out.println(sql);
                    Statement s = mdb.createStatement();
                    ResultSet rs = s.executeQuery(sql);
                    int count = 0;
                    while (rs.next()) {
                        try {
                            /************
                             * All we have done so far is find files that need
                             * to be processed. The next block of code
                             * instantiates a DataFileProcessor, sets its fields
                             * and then starts it, which ultimately processes
                             * the file content, accoring to the class name
                             * stored in the app_class field.
                             */
                            DataFileProcessor fileProcessor = (DataFileProcessor) Class.forName(
                                    rs.getString("app_class")).newInstance();
                            String path = rs.getString("Path");
                            fileProcessor.setFile(new File(path));
                            File f = fileProcessor.getFile();
                            if (!f.exists()) {
                                System.out.println("File specified does not exist: '" + f.getAbsolutePath() + "'");
                                Statement s2 = mdb.createStatement();
                                s2.execute("delete from data_files where Path='" + path + "'");
                                s2.close();
                            } else {
                                fileProcessor.setAppName(rs.getString("Name"));
                                fileProcessor.setSensorID(rs.getInt("Sensor_ID"));
                                // fileProcessor.setTypeID(typeID);
                                fileProcessor.setOffset(rs.getInt("Record_Offset"));
                                fileProcessor.setStatus(rs.getInt("Status"));
                                fileProcessor.setAppID(rs.getInt("App_ID"));
                                fileProcessor.setFileID(rs.getInt("File_ID"));
                                fileProcessor.setDataFileMonitor(this);
                                fileProcessors.addElement(fileProcessor);
                                fileProcessor.start();
                                count++;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (count == 0) {
                        // No files to process so sleep for 10 seconds
                        Thread.sleep(waitInterval);
                    }
                    rs.close();
                    s.close();
                } else {
                    // Too many threads in progress, sleep for 10 seconds
                    Thread.sleep(waitInterval);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}